<?php

class ResourceController extends Controller
{
    public $menu = array(
        array(
            'label' =>  '平台资源',
        ),
        array(
            'label' =>  '原始日志',
            'icon'  =>  'book',
            'url'   =>  array('/resource/index', 'type'=>ResourceType::Log),
        ),
        array(
            'label' =>  '依赖文件',
            'icon'  =>  'file',
            'url'   =>  array('/resource/index', 'type'=>ResourceType::RelyFile),
        ),
        array(
            'label' =>  '查询输出',
            'icon'  =>  'cog',
            'url'   =>  array('/resource/index', 'type'=>ResourceType::QueryOutput),
        ),
        array(
            'label' =>  '计算输出',
            'icon'  =>  'list',
            'url'   =>  array('/resource/index', 'type'=>ResourceType::ComputeOutput),
        ),

    );
    
    /**
     * @return array action filters
     * 
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
	 * This is the 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{

		$model = new Resource;
		if(isset($_GET['Resource'])) {
			$model->attributes = $_GET['Resource'];
		}
		
        $criteria = new CDbCriteria;
        if(isset($_GET['id'])) {
            $task = Task::model()->with('job')->findByPk($_GET['id']);
            $resIds = array();
            $job_param = CJSON::decode($task->job->job_param);
            foreach($job_param['outputs'] as $output) {
                $resIds[] = $output['resource']['res_id'];
            }
            $criteria->addInCondition('res_id', $resIds);
        }
        if(isset($_GET['type'])) {
            $criteria->compare('res_type', $_GET['type']);
        }
        $dataProvider = new CActiveDataProvider('Resource', array(
            	'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $this->render('index', array(
            'dataProvider'  =>	$dataProvider,
        	'model'			=>	$model,
        	'type'			=>	$_GET['type'],
        ));
	}

    public function actionCreate()
    {
        $model=new Resource;
        if(isset($_POST['Resource']))
        {
		    $model->attributes = $_POST['Resource'];
            $model->res_desc = $_POST['Resource']['res_desc'];
            if($model->save()) {
                $this->redirect(array('index'));
            }          
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
    
	public function actionCreatePhysical()
    {
        $model=new ResourcePhysical;
        if(isset($_POST['ResourcePhysical']))
        {
		    $model->setAttributes($_POST['ResourcePhysical'], false);
            if($model->save()) {
                $this->redirect(array('physical'));
            }          
        }

        $this->render('createphysical',array(
            'model'=>$model,
        ));
    }


    public function actionDelete($id)
    {

        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $model=Resource::model()->findByPk($id);
            $model->delete();

            // if ajax request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_get['ajax']))
                $this->redirect(array('index'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

    }

    /**
     *  Updates a particular model.
     *  If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdate($id)
    {
        $model=Resource::model()->findByPk($id);
        if(isset($_POST['Resource']))
        {
            $model->attributes=$_POST['Resource'];
            $model->res_desc = $_POST['Resource']['res_desc'];
            if($model->save())
                $this->redirect(array('index'));
        }

        $this->render('create',array(
            'model'=>$model,
        ));
    }
    
	/**
     *  Updates a particular model.
     *  If update is successful, the browser will be redirected to the 'view' page.
     */
    public function actionUpdatePhysical($id)
    {
        $model=ResourcePhysical::model()->findByPk($id);
        if(isset($_POST['ResourcePhysical']))
        {
            $model->attributes=$_POST['ResourcePhysical'];
            if($model->save())
                $this->redirect(array('physical'));
        }

        $this->render('createphysical',array(
            'model'=>$model,
        ));
    }

    public function actionPhysical()
	{
   		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
        $criteria = new CDbCriteria;

        if(isset($_GET['id'])) {
            $criteria->addCondition('res_id='.$_GET['id']);
        }
        $dataProvider = new CActiveDataProvider('ResourcePhysical', array(
            	'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $this->render('physical', array(
            'dataProvider'  => $dataProvider,
            'type'          => $_GET['type'],
        ));
	}

    public function actionPartition() 
    {
        $criteria = new CDbCriteria;

        $criteria->with = 'physical';
        if(isset($_GET['id'])) {
            $criteria->addCondition('physical.physical_id='.$_GET['id']);
        }
        $dataProvider = new CActiveDataProvider('ResourcePartition', array(
            	'pagination'    =>  array(
                'pageSize'  =>  20,
            ),
            'criteria'  =>  $criteria,
        ));
        $resPhysical = ResourcePhysical::model()->findByPk($_GET['id']);
        $this->render('partition', array(
            'dataProvider'  => $dataProvider,
            'res_id'   => $resPhysical->res_id,
        ));

    }

    /**
	 * This is the 'view' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionView($id)
	{
        // check the partition is exists
        $partitionCount = ResourcePartition::model()->countByAttributes(array('physical_id'=>$id));
        if($partitionCount == 0) {
            Yii::app()->user->setFlash('warning', "<strong>数据传输未完成，请稍候查看...</strong>");
            $this->redirect(array('physical'));
        }
        else {

            // show the partiton result
            $physical = ResourcePhysical::model()->findByPk($id);

            $count=Yii::app()->dwmart->createCommand("SELECT COUNT(*) FROM $physical->storage")->queryScalar();
            $sql="SELECT * FROM $physical->storage";
            $dataProvider=new CSqlDataProvider($sql, array(
                'id'=>'user',
                'totalItemCount'=>$count,
                'sort'=>array(
                    'attributes'=>array(
                        'tv_sec', 'mid', 'ip'
                    ),
                ),
                'db'=>Yii::app()->dwmart,
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));

            $this->render('view', array(
                'dataProvider'  => $dataProvider,
            ));
        }

    }
    
	public function actionAjaxDelete()
    {
        $autoIdAll = $_POST['autoId'];

        if(count($autoIdAll)>0) {
            $count = Resource::model()->deleteByPk($autoIdAll);
            $idList = implode(',', $autoIdAll);
            if($count == count($autoIdAll)) {
                Yii::log("resource[$idList] was deleted successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
            }
            else {
                Yii::log("resource[$idList] was deleted failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
            }
        }
    }
    
    public function actionAjaxDeletePhysical()
    {
        $autoIdAll = $_POST['autoId'];

        if(count($autoIdAll)>0) {
            $count = ResourcePhysical::model()->deleteByPk($autoIdAll);
            $idList = implode(',', $autoIdAll);
            if($count == count($autoIdAll)) {
                Yii::log("resource physical[$idList] was deleted successfully", CLogger::LEVEL_INFO, FRONTEND_LOG);
            }
            else {
                Yii::log("resource physical[$idList] was deleted failed", CLogger::LEVEL_ERROR, FRONTEND_LOG);
            }
        }
    }
    
    public function actionDownload($id)
    {
        ini_set('memory_limit', '2048M');
        /** PHPExcel */
        include_once(dirname(dirname(__FILE__)).'/vendors/PHPExcel/Classes/PHPExcel.php');

        /** PHPExcel_Writer_Excel2007 */
        include_once(dirname(dirname(__FILE__)).'/vendors/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php');
        
        $physicalResource = ResourcePhysical::model()->findByPk($id);
        $datas=Yii::app()->dwmart->createCommand("SELECT * FROM {$physicalResource->storage}")->queryAll();

        // Create new PHPExcel object
        $objPHPExcel = new PHPExcel();

        // Set properties
        $objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setSubject("Office 2007 XLSX Test Document");
        $objPHPExcel->getProperties()->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.");

        // Add data
        $objPHPExcel->setActiveSheetIndex(0);
        $objPHPExcel->setActiveSheetIndex(0)  
             ->setCellValue('A1','时间')  
             ->setCellValue('B1','用户标识')  
             ->setCellValue('C1','IP地址')  
             ->setCellValue('D1','文件路径')  
             ->setCellValue('E1','安全等级'); 

        $i = 2;
        foreach($datas as $data) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A'.$i, date('Y-m-d H:i:s', $data['time']));
            $objPHPExcel->getActiveSheet()->SetCellValue('B'.$i, $data['mid']);
            $objPHPExcel->getActiveSheet()->SetCellValue('C'.$i, $data['ip']);
            $objPHPExcel->getActiveSheet()->SetCellValue('D'.$i, urldecode($data['path']));
            $objPHPExcel->getActiveSheet()->SetCellValue('E'.$i, $data['level']);
            $i++;
        }
        // Rename sheet
        $objPHPExcel->getActiveSheet()->setTitle('日志记录');

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8');  
        header('Content-Disposition: attachment;filename='.urlencode("report.xlsx"));  
        header('Cache-Control: max-age=0');  
        // Save Excel 2007 file
        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save('php://output');
        Yii::app()->end();

    }
}
